# 安装 pymongo    --  pip install pymongo
import pymongo

def connect2mongo():
    try:
        # 1.连接mongod 的服务
        monogo_py = pymongo.MongoClient()
        # 2.库和表的名字    如果有数据会自动建库建表
        # 数据库
        db = monogo_py['db_test']
        # 表  集合
        collection = db['stu']
        # 3. 插入数据
        stu_data = {"name":"xiaomeng","age":27,"gender":True}
        # 文档型数据库
        collection.insert_one(stu_data)
    except Exception as e:
        print(e)
    finally:
        # 4. 关闭数据库
        monogo_py.close()


# connect2mongo()


# 插入多条数据
def insertMany():
    try:
        # 1.连接mongod 的服务
        monogo_py = pymongo.MongoClient()
        # 2.库和表的名字    如果有数据会自动建库建表
        # 数据库
        db = monogo_py['db_test']
        # 表  集合
        collection = db['stu']
        # 3. 插入多条数据
        stu_data_list = [
            {"name": "xiaomeng_1", "age": 27, "gender": True},
            {"name": "xiaomeng_2", "age": 28, "gender": False},
            {"name": "xiaomeng_3", "age": 29, "gender": True},
        ]
        # 文档型数据库
        collection.insert_many(stu_data_list)
    except Exception as e:
        print(e)
    finally:
        # 4. 关闭数据库
        monogo_py.close()


# 删除数据
def deleteData():
    try:
        # 1.连接mongod 的服务
        monogo_py = pymongo.MongoClient()
        # 2.库和表的名字    如果有数据会自动建库建表
        # 数据库
        db = monogo_py['db_test']
        # 表  集合
        collection = db['stu']
        # 4.删除数据  --  一条数据
        # collection.delete_one({"age",27})
        # collection.delete_many({"age": 27})
        collection.delete_one({"age": 28})
    except Exception as e:
        print(e)
    finally:
        # 4. 关闭数据库
        monogo_py.close()

# deleteData()

#  修改数据   -- 一条数据
def update_data():
    try:
        monogo_py = pymongo.MongoClient()
        collection = monogo_py['db_test']['stu']
        collection.update({"age":29},{"$set":{"name":"wangwu"}})
    except Exception as e:
        print(e)
    finally:
        monogo_py.close()

# update_data()


# 修改多条数据
def update_data_many():
    try:
        monogo_py = pymongo.MongoClient()
        collection = monogo_py['db_test']['stu']
        # collection.update({"age":29},{"$set":{"name":"wangwu"}})
        collection.update_many({"name":"wangwu"},{"$set":{"age":22}})
    except Exception as e:
        print(e)
    finally:
        monogo_py.close()

# update_data_many()

# 查询数据
def find_data():
    try:
        monogo_py = pymongo.MongoClient()
        collection = monogo_py['db_test']['stu']
        # collection.update({"age":29},{"$set":{"name":"wangwu"}})
        # 查询
        result = collection.find({"age":22})  # 返回的是一个游标对象  --  查询多个

        # print(result)
        for data in result:
            print(data)
    except Exception as e:
        print(e)
    finally:
        monogo_py.close()


find_data()





